<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import type { LoginUserModifyCmd } from '@/apis/common/loginApi'
import { reactive, ref } from 'vue'
import { loginApi } from '@/apis/common/loginApi'

const emits = defineEmits(['success'])
const visible = ref(false)
const loading = ref(false)
const formRef = ref<FormInstance>()
const formRules = reactive<FormRules<LoginUserModifyCmd>>({
  phone: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
  email: [{ required: true, message: '请输入电子邮箱', trigger: 'blur' }],
  captchaCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
})
const formData = ref<LoginUserModifyCmd>()
const countdown = ref(0)
const modifyField = ref<'email' | 'phone'>()

function sendCaptchaCode() {
  formRef.value?.validateField(modifyField.value, async (valid: boolean) => {
    if (valid && formData.value) {
      loading.value = true
      try {
        if (modifyField.value === 'email') {
          await loginApi.sendCaptcha({ type: 'MODIFY_EMAIL', target: formData.value.email! })
          ElMessage.success('邮件已发送')
        }
        else if (modifyField.value === 'phone') {
          await loginApi.sendCaptcha({ type: 'MODIFY_PHONE', target: formData.value.phone! })
          ElMessage.success('短信已发送')
          visible.value = false
        }
        startCountdown(30)
      }
      finally {
        loading.value = false
      }
    }
  })
}

/**
 *
 * @param time 开始倒计时
 */
function startCountdown(time: number) {
  countdown.value = time
  if (time <= 0) {
    return
  }
  setTimeout(() => {
    startCountdown(time - 1)
  }, 1000)
}

function onSubmit() {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid && formData.value) {
      await loginApi.modifyLoginUser(formData.value)
      ElMessage.success('保存成功')
      visible.value = false
      emits('success')
    }
  })
}

function open(type: 'email' | 'phone') {
  modifyField.value = type
  visible.value = true
  formData.value = {}
}
defineExpose({ open })
</script>

<template>
  <el-dialog
    v-model="visible"
    destroy-on-close
    width="500px"
    :title="`修改${modifyField === 'phone' ? '手机号码' : '电子邮箱'}`"
  >
    <el-form
      v-if="formData"
      ref="formRef"
      :model="formData"
      label-width="auto"
      :rules="formRules"
      class="m-5"
    >
      <el-form-item
        v-if="modifyField === 'phone'"
        label="手机号码" prop="phone"
      >
        <el-input v-model="formData.phone" />
      </el-form-item>
      <el-form-item
        v-if="modifyField === 'email'"
        label="电子邮箱" prop="email"
      >
        <el-input v-model="formData.email" />
      </el-form-item>
      <el-form-item label="验证码" prop="captchaCode">
        <el-input v-model="formData.captchaCode">
          <template #append>
            <el-button v-if="countdown <= 0" :loading="loading" @click="sendCaptchaCode">
              获取验证码
            </el-button>
            <template v-else>
              重新获取({{ countdown }}秒)
            </template>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <div class="w-full flex flex-row justify-end">
          <el-button @click="visible = false">
            取消
          </el-button>
          <el-button type="primary" @click="onSubmit">
            提交
          </el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
